import { baseURL } from '@/utils/config'
import { getIdentity } from '@/utils/index'
import { RefreshToken } from '@/api/member'
export default async function request<T>(requestOption: RequestOption): Promise<ResponseData<T>> {
  const { url, data = {}, method = 'GET', loading = true,host ='' } = requestOption

  return new Promise((resolve, reject) => {
    if(requestOption.loading) {
      uni.showLoading({
        title: '加载中...',
        mask: true
      })
    }
    const option: UniNamespace.RequestOptions = {
      url: `${baseURL}${requestOption.host}/${requestOption.url}`,
      method: requestOption.method || 'GET',
      data: requestOption.data || {},
      header: {
        'content-type': 'application/json;charset=utf-8',
        Authorization : `Bearer ${uni.getStorageSync('mobiletoken')}`,
        visitor: getIdentity()
      },
      success: (res:any) => {
        if (res.statusCode === 401) { //没权限
          const refreshToken = uni.getStorageSync('mobileRefreshToken')
          if(refreshToken) {
            RefreshToken(refreshToken).then((res:any)=> {
              if(res.success) {
                uni.setStorageSync('mobiletoken', res.data.accessToken)
                option.header.Authorization = `Bearer ${res.data.accessToken}`
                uni.request(option)
              }
            })
          } else {
            return uni.navigateTo({
              url: '/pages/user/login/login'
            })
          }
        }
        if (res.statusCode === 403) {
          uni.showToast({
            title: '当前用户无权访问此页面',
            icon: 'none'
          })
        }
        return resolve(res.data);
      
      },
      fail: (error) => {
        requestOption.loading && uni.hideLoading()
        uni.showToast({
          icon: 'none',
          title: '请求失败，请检查网络'
        })
        return resolve({success: false,msg: ''});
      }
    }
     uni.request(option)
  })
  
}